package com.hydra.auth.service;

import com.hydra.auth.entity.SysUser;
import com.hydra.auth.repository.SysUserService;
import com.hydra.base.utils.JsonUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.authentication.DisabledException;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;

/**
 * Jwt获取token的服务类
 * @Author Hydra
 * @Date 2022/4/18 11:24
 */
@Slf4j
@Service
public class WebUserDetailsService implements UserDetailsService {

    @Resource
    private SysUserService sysUserRepository;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        SysUser user = sysUserRepository.findByAccount(username);
        if(user == null){
            log.error("登录失败，查询用户名：{}", username);
            throw new UsernameNotFoundException("用户不存在: " + username);
        }
        if (!"1".equals(user.getStatus())) {
            throw new DisabledException("用户已被禁用：" + username);
        }
        log.info("查询用户名：{}， 获取到的用户信息：{}", username, JsonUtil.toJsonString(user));
        return user;
    }

}
